/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fzhucc.modules.SendPro.service;


import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.SendPro.dto.SendProDto;
import com.fzhucc.modules.pms.domain.Project;
import com.fzhucc.modules.pms.domain.ProjectSendPro;
import com.fzhucc.modules.pms.repository.ProjectRepository;
import com.fzhucc.modules.pms.repository.ProjectSendProRepository;
import com.gbs.center.datahub.sdk.auth.ClientCredentials;
import com.gbs.center.datahub.sdk.client.DatahubClient;
import com.gbs.center.datahub.sdk.client.DatahubClientBuilder;
import com.gbs.center.datahub.sdk.common.config.DatahubConfig;
import com.gbs.center.datahub.sdk.model.dto.RecordEntry;
import com.gbs.center.datahub.sdk.model.dto.RecordSchema;
import com.gbs.center.datahub.sdk.model.dto.TupleRecordData;
import com.gbs.center.datahub.sdk.model.response.DataPushResponse;
import com.google.common.collect.Maps;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * @author yyg
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2023-08-22
 **/
@Service
@RequiredArgsConstructor
public class SendProService {

    //DataHub服务的地址
    @Value("${quanzong.url.prod}")
    public String endpoint;

    @Value("${quanzong.access.key}")
    public String accessKey;

    @Value("${quanzong.access.id}")
    public String accessId;

    @Value("${quanzong.access.secret}")
    public String accessSecret;

    @Value("${quanzong.pro.topic}")
    public String topic;

    @Value("${quanzong.pro.project}")
    public String project;

    @Value("${quanzong.area.code}")
    public String areaCode;

    private final ProjectSendProRepository projectSendProRepository;

    public Boolean deleteById(String pmsId){
        DatahubClient datahubClient = DatahubClientBuilder.newBuilder()
                .setDatahubConfig(new DatahubConfig(endpoint, new ClientCredentials(accessKey, accessSecret)))
                .build();
        List<String> datalds = new ArrayList<String>();
        datalds.add(pmsId);
        datahubClient.deleteRecords(project, topic,datalds);
        return true;
    }


    public DataPushResponse pushPro(SendProDto sendProDto) {
        if (sendProDto.getSendGroup() == null) {
            throw new BadRequestException("缺少分组无法操作");
        }
        DatahubClient datahubClient = DatahubClientBuilder.newBuilder()
                .setDatahubConfig(new DatahubConfig(endpoint, new ClientCredentials(accessKey, accessSecret)))
                .build();
        RecordSchema recordSchema = datahubClient.getTopicData(project, topic).getRecordSchema();
        List<RecordEntry> records = new ArrayList<RecordEntry>();
        List<ProjectSendPro> all = projectSendProRepository.findAllByNormalStatusWithGroup(sendProDto.getSendGroup());
        for (int i = 0; i < all.size(); i++) {
            ProjectSendPro pms = all.get(i);
            Map<String, String> attrMap = Maps.newHashMap();
            attrMap.put("attr1", "attr111111--" + i);
            RecordEntry recordEntry = new RecordEntry();
            recordEntry.setAttributes(attrMap);
            TupleRecordData recordData = new TupleRecordData(recordSchema);
            //recordData.setDataId(accessId);
            recordData.setDataId(pms.getId());//唯一值 用项目id取代
            if (pms.getId() == null) {
                recordData.setField("studio_id", "");//创新工作室id
            } else {
                recordData.setField("studio_id", pms.getId());//创新工作室id  项目id
            }
            if (pms.getEmployer() == null) {
                recordData.setField("studio_name", "暂无");//工作单位没有就填 暂无
            } else {
                recordData.setField("studio_name", pms.getEmployer());//工作单位
            }
            recordData.setField("area_code", areaCode);//当前工会所在区域代码
            if (pms.getProjectName() == null) {
                recordData.setField("name", "");//项目名称
            } else {
                recordData.setField("name", pms.getProjectName());//项目名称
            }
            if (pms.getProjectImgUrl() == null) {
                recordData.setField("cover_img", "https://kccg.fzzgsc.com/webapp/store/projectDefaultImg.png");//封面图 没有就用缺省图
            } else {
                if (pms.getProjectImgUrl().equals("")) {
                    recordData.setField("cover_img", "https://kccg.fzzgsc.com/webapp/store/projectDefaultImg.png");//封面图 没有就用缺省图
                } else {
                    recordData.setField("cover_img", pms.getProjectImgUrl());//封面图
                }
            }
            String url = "https://dzsc.fzzgsc.com/#/subPages/projectStore/sub/projectDetail?id=" + pms.getId() + "&type=全部"; //跳转详情地址
            recordData.setField("link_url_h5", url);//H5访问链接
            recordData.setField("link_url_pc", url);//pc访问链接，如果无PC端，请与H5链接一致

            if (pms.getItemCategory() == null) {
                recordData.setField("industry_category", "");//行业分类
            } else {
                recordData.setField("industry_category", pms.getItemCategory());//行业分类
            }
            if (pms.getRaceDomain() == null) {
                recordData.setField("label_info", "");//用“|”进行文字分割，如“优化设计|减少零件品种|降低成本”等
            } else {
                recordData.setField("label_info", pms.getRaceDomain());//用“|”进行文字分割，如“优化设计|减少零件品种|降低成本”等    暂时填所属领域
            }
            recordData.setField("released_time", pms.getCreateTime().getTime());//对外发布时间

            recordEntry.setRecordData(recordData);
            records.add(recordEntry);
        }
        DataPushResponse resp = datahubClient.pushRecords(project, topic, records);
        return resp;
    }


}